<?php
namespace app\controller;

use think\Request;
use think\facade\Db;

class User extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['level', '=', 3] );

		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['username', 'like',  "%{$username}%" ] );
		}

		$nickname = $request->param('nickname', '', 'trim');
		if($nickname) {
			array_push( $where, ['nickname', 'like',  "%{$nickname}%" ] );
		}

		$role = $request->param('role', '', 'trim');
		if($role) {
			array_push( $where, ['role', '=',  $role ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			array_push( $where, ['time', 'between', cloud_datetime_format( $createTimeStart, $createTimeEnd, true) ] );
		}

		$query = Db::name('cfg_user')->where($where)->order($sort, $order)->paginate($limit);

		$items = $query->items();
		foreach($items as &$value) {
			$value['password'] = null;
			$value['roles'] = Db::table('cfg_role')->field('id, roleName')->where('id', $value['role'])->select()->toArray();
		}

		unset($value);

		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $items ];
	}

	/**
	 * 用户授权数
	 *
	 * @return
	 */
	public function getUserCount(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$usernun = Db::table('cfg_user')->where('companyId', $request->sessInfo['companyId'])->where('level', 2)->value('usersnum');
		$countnun = Db::table('cfg_user')->where('companyId', $request->sessInfo['companyId'])->where('level', 3)->count();
		return ['code'=>0, 'msg'=>'操作成功', 'usernun' => $usernun, 'countnun' => $countnun ];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			Db::name('cfg_user')
					->where('id', $param['state'])
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'status' => $status]);
			return ['code'=>0, 'msg'=>'操作成功'];
		}

		$id = $request->param('id', '', 'trim');
		$email = $request->param('email', '', 'trim');
		$logincity = $request->param('logincity', '', 'trim');
		$loginip = $request->param('loginip', '', 'trim');
		$logintime = $request->param('logintime', '', 'trim');
		$nickname = $request->param('nickname', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$phone = $request->param('phone', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$role = $request->param('role', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$wechat = $request->param('wechat', '', 'trim');
		$status = $request->param('status', '', 'trim');
		if($password) {
			$password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
			Db::name('cfg_user')
					->where('id', $id)
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'password' => $password]);
		}
		Db::name('cfg_user')
				->where('id', $id)
				->where('companyId', $request->sessInfo['companyId'])
				->update([ 'email' => $email, 'logincity' => $logincity, 'nickname' => $nickname, 'phone' => $phone, 'remark' => $remark, 'role' => $role,
				'loginip' => $loginip, 'logintime' => $logintime, 'status' => $status, 'wechat' => $wechat]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$email = $request->param('email', '', 'trim');
		$logincity = $request->param('logincity', '', 'trim');
		$loginip = $request->param('loginip', '', 'trim');
		$logintime = $request->param('logintime', '', 'trim');
		$nickname = $request->param('nickname', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$phone = $request->param('phone', '', 'trim');
		$remark = $request->param('remark', '', 'trim');
		$role = $request->param('role', '', 'trim');
		$username = $request->param('username', '', 'trim');
		$wechat = $request->param('wechat', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$query = Db::table('cfg_user')->where('username', $username)->value('username');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'操作失败, 用户已存在!'];
		}

    $usersnum = Db::table('cfg_user')->where('companyId', $request->sessInfo['companyId'])->where('level', 2)->value('usersnum');
		if( $usersnum > 1) {
			$countnum = Db::table('cfg_user')->where('companyId', $request->sessInfo['companyId'])->where('level', 3)->count();
			if( $countnum >= $usersnum ) {
				return json(['msg' => '新增子用户上限, 你的账户授权子用户为'.$usersnum.'个, 请联系管理员!', 'access_token' => null, 'code' => 403, 'token_type' => null]);
			}
		}

		$password = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
		Db::name('cfg_user')->insert([ 'companyId' => $request->sessInfo['companyId'], 'email' => $email, 'level' => 3,
			'logincity' => $logincity, 'loginip' => $loginip, 'logintime' => $logintime, 'nickname' => $nickname,
			'password' => $password, 'phone' => $phone, 'remark' => $remark, 'role' => $role, 'status' => $status,
			'username' => $username, 'wechat' => $wechat, 'datatime' => date('Y-m-d H:i:s')]);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'user:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$beginTime = microtime(true);
		$delTemp = [];
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			array_push($delTemp, Db::table('cfg_user')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->value('username'));
			Db::table('cfg_user')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->where('level', 3)->delete();
		}
		unset($explode, $value);
		foreach( $delTemp as $value ) {
			if( $value ) {
				$endTime = microtime(true);
				$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
				$request->sessInfo['username'], round($endTime - $beginTime, 3), '用户管理', '删除用户['.$value.']', 0, json_encode($param));
			}
		}
		unset($delTemp, $value);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 查询用户
	 *
	 * @return
	 */
	public function query(Request $request)
	{
		$username = $request->param('username', '', 'trim');
		$query = Db::table('cfg_user')->where('username', $username)->value('username');
		if(empty($query)){
			return json(['code'=>0, 'data' => [], 'msg'=>'']);
		}
		return json(['code'=>0, 'data' => [['username' => $query]], 'msg'=>'']);
	}

	/**
	 * 用户接口
	 *
	 * @return
	 */
	public function getAccount(Request $request)
	{
		// 高级用户
		$authorities = [];
		if( $request->sessInfo['level'] < 3) {
			$queryArray = Db::table('cfg_menu')->field('authority')->where('menuType', 1)->whereNotLike('authority', '%:read%')->select()->toArray();
			foreach($queryArray as $value){
				if($value['authority']) {
					array_push($authorities, $value['authority']);
				}
			}
			return json(['code' => 0, 'msg' =>'', 'data' => [
				 'username' => $request->sessInfo['username'],
				 'nickname' => $request->sessInfo['nickname'],
				 'company' => $request->sessInfo['company'],
				 'expires' => $request->sessInfo['expires'],
				 'authorities' => $authorities
			]]);
		}

		// 普通用户
		$menuId = $this->cfg_getRoleValue($request->sessInfo['id']);
		if( $menuId == false ) {
			return json(['code' => 0, 'msg' =>'', 'data' => [
				 'username' => $request->sessInfo['username'],
				 'nickname' => $request->sessInfo['nickname'],
				 'company' => $request->sessInfo['company'],
				 'expires' => $request->sessInfo['expires'],
				 'authorities' => $authorities
			]]);
		}
		$queryArray = Db::table('cfg_menu')->field('authority')->where('menuType', 1)->where('menuId', 'in', $menuId)
		  ->whereNotLike('authority', '%:read%')->select()->toArray();
		foreach($queryArray as $value){
			if($value['authority']) {
				array_push($authorities, $value['authority']);
			}
		}
		return json(['code' => 0, 'msg' =>'', 'data' => [
			'username' => $request->sessInfo['username'],
			'nickname' => $request->sessInfo['nickname'],
			'company' => $request->sessInfo['company'],
			'expires' => $request->sessInfo['expires'],
			'authorities' => $authorities
		]]);
	}

}
